激活函数
好的,以下是对常见的四种激活函数的详细对比分析及其使用场景:
特点:
优点:
缺点:
使用场景:
特点:
优点:
缺点:
使用场景:
特点:
优点:
缺点:
使用场景:
其中
特点:
优点:
缺点:
使用场景:
激活函数 | 输出范围 | 是否有梯度消失 | 输出中心 | 计算效率 | 常见应用 |
---|---|---|---|---|---|
Sigmoid | (0, 1) | 有 | 非零 | 低 | 二分类输出层 |
Tanh | (-1, 1) | 有,但较少 | 零 | 低 | 隐藏层,时间序列 |
ReLU | [0, ∞) | 无 | 非零 | 高 | 隐藏层,卷积神经网络 |
Leaky ReLU | (-∞, ∞) | 无 | 非零 | 高 | 隐藏层,解决 ReLU 缺陷 |
Sigmoid:
Tanh:
ReLU:
Leaky ReLU:
通过合理选择激活函数,可以显著提高神经网络的训练效率和性能,针对不同任务和网络架构选择合适的激活函数是模型设计中的重要一步。
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
# 定义变量
x = sp.symbols('x')
# 定义激活函数
sigmoid = 1 / (1 + sp.exp(-x))
tanh = sp.tanh(x)
relu = sp.Piecewise((0, x < 0), (x, x >= 0))
leaky_relu = sp.Piecewise((0.01*x, x < 0), (x, x >= 0))
# 转换为可计算的函数
sigmoid_func = sp.lambdify(x, sigmoid, 'numpy')
tanh_func = sp.lambdify(x, tanh, 'numpy')
relu_func = sp.lambdify(x, relu, 'numpy')
leaky_relu_func = sp.lambdify(x, leaky_relu, 'numpy')
# 定义x的范围
x_vals = np.linspace(-10, 10, 400)
# 计算激活函数的值
sigmoid_vals = sigmoid_func(x_vals)
tanh_vals = tanh_func(x_vals)
relu_vals = relu_func(x_vals)
leaky_relu_vals = leaky_relu_func(x_vals)
# 创建图形
plt.figure(figsize=(10, 8))
plt.subplot(2, 2, 1)
plt.plot(x_vals, sigmoid_vals, label='Sigmoid')
plt.title('Sigmoid Activation Function')
plt.xlabel('x')
plt.ylabel('σ(x)')
plt.grid(True)
plt.legend()
plt.subplot(2, 2, 2)
plt.plot(x_vals, tanh_vals, label='Tanh', color='orange')
plt.title('Tanh Activation Function')
plt.xlabel('x')
plt.ylabel('tanh(x)')
plt.grid(True)
plt.legend()
plt.subplot(2, 2, 3)
plt.plot(x_vals, relu_vals, label='ReLU', color='green')
plt.title('ReLU Activation Function')
plt.xlabel('x')
plt.ylabel('ReLU(x)')
plt.grid(True)
plt.legend()
plt.subplot(2, 2, 4)
plt.plot(x_vals, leaky_relu_vals, label='Leaky ReLU', color='red')
plt.title('Leaky ReLU Activation Function')
plt.xlabel('x')
plt.ylabel('Leaky ReLU(x)')
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()